<template>
    <!-- <el-container style="padding:  0 200px;" class="spc">
        <el-aside style="padding:0px 15px;">
            <div class="ddleft">
                11
            </div>
        </el-aside>
        <el-main style="padding:0px 15px;">
            <div class="ddright">
                11
            </div>
        </el-main>
    
    </el-container> -->
    <div style="padding: 0 200px;">
        <div style="background-color: white;" class="dd">
            <el-row>
                <el-col :span="24">
                    <div class="grid-content">
                        <h2>我的购物车</h2>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-table :data="shopCartData" style="width: 100%" class="" ref="table"
                    @selection-change="selectionChangeHandle">
                    <el-table-column lable="全选" type="selection" width="55">
                    </el-table-column>
                    <el-table-column prop="drug.img" label="图片" width="180">
                        <template slot-scope="{ row }">
                            <el-image style="width: auto; height: 40px; border:none;cursor: pointer;"
                                :src="getImage(row.drug.img)"
                                :preview-src-list="[`http://localhost:8081/common/download?name=${row.drug.img}`]">
                                <div slot="error" class="image-slot">
                                    <img src="" style="width: auto; height: 40px; border:none;">
                                </div>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="drug.drugName" label="名称" width="180">
                    </el-table-column>
                    <el-table-column prop="drug.price" label="单价">
                    </el-table-column>
                    <el-table-column prop="count" label="数量">
                        <template slot-scope="scope">
                            <div class="amount-warp">
                                <input class="border" @input="cartDrugsAmountChange($event, scope.row)"
                                    v-model="scope.row.count" />
                                <div class="quick-button">
                                    <i class="border el-icon-arrow-up" @click="addAmountCount(scope.row)"></i>
                                    <i class="border el-icon-arrow-down" @click="subtractAmountCount(scope.row)"></i>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sum" label="小计">
                        <template slot-scope="scope">
                            {{ getNum(scope) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="删除" placement="top">
                                <el-button size="mini" type="danger" icon="el-icon-delete"
                                    @click="deleteCartByDrugId(scope.row)" />
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <el-col :span="24">
                    <div class="sprice">
                        合计：{{ sumPrice }}
                    </div>
                    <div style="text-align: right;padding: 10px 0px;">
                        <el-button style="width: 150px;font-size: 18px;margin-right: 30px;"
                            @click="commitOrder" :disabled="shopCartData.length==0||selectedItem.length==0">提交订单</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="10" class="addressbox">
                <el-card>
                    <el-col :span="6" v-for="(item, index) in addrList" :key="index">
                        <el-card :class="num == item.id ? 'sactive' : ''" @click.native="chooseAddr(item.id)">
                            <el-row>
                                <el-col :span="18">
                                    <div>{{ item.name }}<span :class="item.selected == 0 ? 'qc' : ''">[默认地址]</span></div>
                                    <div>{{ item.phone }}</div>
                                    <div>{{ item.province + item.city + item.country + item.detail }}</div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="an">
                                        <el-button type="primary" @click="editShow(item)">编辑</el-button>
                                        <el-popconfirm title="确定删除该地址吗  ？">
                                            <el-button slot="reference" type="warning"
                                                @click="deleteAddr(item.id)">删除</el-button>
                                        </el-popconfirm>

                                    </div>
                                </el-col>
                            </el-row>
                        </el-card>
                    </el-col>
                </el-card>

            </el-row>
        </div>
        <!-- 修改地址的对话框 -->
        <el-dialog title="修改地址" :visible.sync="addressVisible" width="50%" height="auto">
            <el-form :model="form" ref="addressfrom">
                <el-form-item prop="name" label="收货人" label-width="120px">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="phone" label="手机号" label-width="120px">
                    <el-input v-model="form.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="地址" label-width="120px" prop="selectedOptions">
                    <el-cascader size="large" :options="options" v-model="form.selectedOptions" @change="addressChange">
                    </el-cascader>
                </el-form-item>
                <el-form-item prop="detail" label="详细地址" label-width="120px">
                    <el-input v-model="form.detail" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addressVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOrUpdateAddress">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
export default {
    name: "ShopCart",
    data() {
        return {
            shopCartData: [],//表格数据
            selectedItem: [],//购物车当前选中选
            sumPrice: 0,
            addrList: [],//地址列表
            num: 0,
            addressVisible: false,
            form: {},
            options: regionData,
        }
    },
    created() {
        this.getShopCartList()
        this.getAddressList()
    },
    methods: {
        addressChange(value) {
            //打印数据
            console.log("这时候", this.selectedOptions)
        },
        addOrUpdateAddress() {//保存地址信息
            this.form.customerId = JSON.parse(localStorage.getItem("customer")).id
            this.form.province = CodeToText[this.form.selectedOptions[0]]
            this.form.city = CodeToText[this.form.selectedOptions[1]]
            this.form.country = CodeToText[this.form.selectedOptions[2]]
            console.log("当前111", this.form)
            this.request.post("/address", this.form).then(res => {
                if (res.code == 200) {
                    this.$message.success("地址修改成功")
                    this.getAddressList()
                }
            })
            this.addressVisible = false
        },
        editShow(item) {
            //打开修改地址弹窗 发起修改地址请求
            this.addressVisible = true
            this.form = JSON.parse(JSON.stringify(item))
            console.log("当前123", this.from)
            this.request.get("/address/" + item.id).then(res => {
                if (res.code == 200) {
                    let addr = res.data
                    //回显地址级联框
                    this.form.selectedOptions = [TextToCode[addr.province].code, TextToCode[addr.province][addr.city].code, TextToCode[addr.province][addr.city][addr.country].code]
                    console.log(this.selectedOptions + "123")
                }
            })
        },
        cartDrugsAmountChange(e, orderInfo) {
            if (e.target.value > orderInfo.drug.stock) {
                orderInfo.count = orderInfo.drug.stock
                return this.$message.error('当前库存为' + orderInfo.drug.stock + '件')
            }
            if (e.target.value <= 0) {
                orderInfo.count = 1
                return this.$message.error('药物数量不能小于0')
            }
            var shopcart = {}
            shopcart.id = orderInfo.id
            shopcart.count = orderInfo.count
            this.updateShopCartDrugCount(shopcart)

        },
        updateShopCartDrugCount(shopcart) {
            this.request.post("/shopcart", shopcart).then(res => {
                if (res.code == 200) {
                }
            })
        },
        // 药物数量加1
        addAmountCount(orderInfo) {
            ++orderInfo.count
            if (orderInfo.count > orderInfo.drug.stock) {
                this.$message.error('当前库存为' + orderInfo.drug.stock + '件')
                orderInfo.count = orderInfo.drug.stock
            }
            var shopcart = {}
            shopcart.id = orderInfo.id
            shopcart.count = orderInfo.count
            this.updateShopCartDrugCount(shopcart)
            this.changeSumPrice()

        },
        // 药物数量减1
        subtractAmountCount(orderInfo) {
            if (orderInfo.count <= 1) {
                return this.$message.error('药物数量不能小于1')
            }
            --orderInfo.count
            var shopcart = {}
            shopcart.id = orderInfo.id
            shopcart.count = orderInfo.count
            this.updateShopCartDrugCount(shopcart)
            this.changeSumPrice()
        },
        deleteCartByDrugId(value) {
            //删除购物车数据 根据购物车id
            console.log("当前value=>", value)
            this.request.delete("/shopcart/" + value.id).then(res => {
                if (res.code == 200) {
                    this.$message.success("删除成功")
                    this.getShopCartList()
                }
            })
        },
        changeSumPrice() {
            //多选框改变时 改变合计总价
            console.log("当前selection==>",)
            this.selectedItem = []
            var list = this.$refs.table.selection
            console.log("当前药物==>", this.$refs.table.selection)
            list.forEach((item, index) => {
                this.selectedItem[index] = item.id
            })
            console.log("当前val==>", this.selectedItem)
            this.sumPrice = 0
            list.forEach(item => {
                this.sumPrice += item.drug.price * item.count
            })
        },
        deleteAddr(id) {
            this.request.delete("/address/" + id).then(res => {
                if (res.code == 200) {
                    this.$message.success("删除成功")
                    this.getAddressList()
                }
            })
        },
        chooseAddr(index) {
            //获取当前选择地址
            this.num = index
            console.log("当前index==>", index)
        },
        getAddressList() {//获取用户地址列表
            let id = JSON.parse(localStorage.getItem("customer")).id
            console.log(id)
            this.request.get("/customer/address/" + id).then(res => {
                if (res.code == 200) {
                    this.addrList = res.data
                    this.addrList.forEach(item => {
                        if (item.selected) {
                            this.num = item.id
                        }
                    })
                }
            })
        },
        getShopCartList() {
            //获取购物车列表数据
            var id = JSON.parse(localStorage.getItem("customer")).id
            this.request.get("/shopcart/" + id).then(res => {
                if (res.code == 200) {
                    this.shopCartData = res.data
                    console.log("当前shopdata==>", res.data)
                    this.$nextTick(() => {
                        this.toggleSelection(this.shopCartData);
                    });
                }
            })
        },
        selectionChangeHandle(val) {
            //根据单选框是否选中 进行数据回传 
            this.selectedItem = []
            console.log("当前药物==>", val)
            val.forEach((item, index) => {
                this.selectedItem[index] = item.id
            })
            this.sumPrice = 0
            val.forEach(item => {
                this.sumPrice += item.drug.price * item.count
            })
            //对选中的药物进行保存处理
            this.request.post("/shopcart/changeSelectShop", this.selectedItem).then(res => {
                console.log(res);
            })

        },
        getImage(img) {
            return "http://localhost:8081/common/download?name=" + img
        },
        getNum(scope) {
            //获取总价
            var price = scope.row.drug.price
            var count = scope.row.count
            return parseFloat(price * count)
        },
        getSum() {
        },
        commitOrder() {
            //提交订单
            var customer = JSON.parse(localStorage.getItem("customer"))
            console.log("成功",customer)
            this.request("/shopcart/shopCartToOrderByCustomerId/"+customer.id).then(res => {
                if(res.code==200){
                    console.log("提交订单成功")
                    console.log("提交订单成功",res)
                    this.$router.push("/front/orderDetail/"+res.msg)
                }
            })
        },
        toggleSelection(rows) {
            //表格全选
            if (rows) {
                rows.forEach((item) => {
                    //设置该表格选框选中
                    if (item.selected == 1) {
                        this.$refs.table.toggleRowSelection(item);
                    }
                });
            } else {
                this.$refs.table.clearSelection();
            }
        },
    }
}
</script>

<style lang="less" scoped>
.amount-warp {
    display: flex;

    input {
        width: 31px;
        height: 31px;
        line-height: 30px;
        padding-left: 10px;
        outline: none;
    }

    .quick-button {
        i {
            display: block;
            width: 30px;
            height: 16px;
            border-left: none;
            text-align: center;
            line-height: 16px;
            cursor: pointer;
        }

        .el-icon-arrow-up {
            border-bottom: none;
        }

        .el-icon-arrow-down {}
    }

    .quick-button i:hover {
        color: #EF001C;
    }
}

.qc {
    display: none;
}

.sactive {
    border: 1px solid yellowgreen;
}

.el-table {
    font-size: 15px;
    font-weight: lighter;
    font-weight: normal;
}

.dd {
    background-color: white;

    h2 {
        font-size: 18px;
        font-weight: lighter;
        padding: 20px;
        border-bottom: 1px solid #E6E6E6;

    }

    .sprice {
        color: orangered;
        line-height: 50px;
        height: 50px;
        font-size: 20px;
        text-align: right;
        margin-right: 200px;
    }

    .addressbox {
        .el-card {
            font-size: 12px;
            margin-bottom: 10px;

        }

        .el-button {
            margin-left: 0px;
        }
    }
}
</style>